How to check whether a string contains a substring in JavaScript?

Problem

Usually I would expect a String.contains() method but there doesn't seem to be one. What is a reasonable way to check for this in javascript ?

Answer

Here is a list of current possibilities:

  • indexOf

    var string = "foo",
    substring = "oo";
    string.indexOf(substring) !== -1;

  • includes

    var string = "foo",
    substring = "oo";
    string.includes(substring);

  • search

    var string = "foo",
    expr = /oo/; // no quotes here
    expr.test(string);

  • RegExp

    var string = "foo",
    expr = /oo/;
    string.match(expr);

  • Match

    var string = "foo",
    expr = /oo/;
    string.search(expr);